<?php

namespace App\Services;

use App\Models\File;
use Illuminate\Http\Request;
use Storage;

class FileService{

    protected $files;
    protected $fileDir;
    protected $fileType =[];
    protected $fileSize = 1024 * 1024 * 10;
    protected $imgType = [
        'image/png', 'image/gif', 'image/jpeg', 'image/bmp', ''
    ];
    protected $imgSize = 1024 * 1024 * 2;

    public function __construct()
    {
        $this->files = request()->file();
    }

    /**
     * 文件上传
     * @param string $uploadType
     * @return array
     */
    public function uploads($uploadType = 'file', $dir = ''){
        $csrf_token = request()->get('_token');
        $resault = [
            'status' => false,
            'message' => '未知错误',
            'url' => []
        ];
        foreach ($this->files as $key => $file) {
            if ($file->isValid()){
                $file_size = $file->getSize(); //大小
                $file_type = strtolower($file->getMimeType()); //类型
                $file_ext = strtolower($file->getClientOriginalExtension()); //扩展名
                $real_path = $file->getRealPath(); //临时文件的绝对路径

                if ($uploadType == 'image'){
                     if (!in_array($file_type, $this->imgType)){
                         $resault['message'] = '图片格式不允许！';
                         break;
                     }
                    if ($file_size > $this->imgSize){
                        $resault['message'] = '图片最大支持'.(human_filesize($this->imgSize)).'！';
                        break;
                    }
                    $this->fileDir = 'images';
                } elseif ($uploadType == 'file'){
                    if (!in_array($file_type, $this->fileType)){
                        $resault['message'] = '文件格式不允许！';
                        break;
                    }
                    if ($file_size > $this->fileSize){
                        $resault['message'] = '文件最大支持'.(human_filesize($this->fileSize)).'！';
                        break;
                    }
                    $this->fileDir = 'file';
                }else{
                    $resault['message'] = '上传类型错误！';
                    break;
                }

                $path = empty($dir)?$this->fileDir:$dir;
                $filename = str_random(20).'.'.$file_ext;
                $file_path = attachment().$path.'/'.date('Ymd').'/'.$filename;
                if(Storage::disk('uploads')->put($file_path, file_get_contents($real_path))){
                    $resault['status'] = true;
                    $resault['message'] = '上传成功！';
                    $resault['url'][] = $file_path;

                    $model = new File();
                    $model->dir = $file_path;
                    $model->mine_type = $file_type;
                    $model->type = $this->fileDir;
                    $model->size = $file_size;
                    $model->save();

                    if (\Session::has('uploads_files')){
                        $file_ids = \Session::get('uploads_files');
                        $file_ids[$csrf_token][] = $model->id;
                    }else{
                        $file_ids[$csrf_token][] = $model->id;
                    }
                    \Session::put('uploads_files', $file_ids);

                }else{
                    $resault['message'] = '上传失败';
                }
            }
        }

        return $resault;
    }

    /**
     * 设置允许文件上传类型
     * @param string $fileType
     */
    public function setFileType($fileType = ''){
        if (!empty($fileType)) $this->fileType = $fileType;
    }

    /**
     * 设置允许图片上传类型
     * @param string $imgType
     */
    public function setImgType($imgType = ''){
        if (!empty($imgType)) $this->imgType = $imgType;
    }

    /**
     * 根据文件id获取文件列表
     * @param $ids
     * @return array
     */
    public function getFilesByIds($ids){
        $resault = [
            'files' => [],
            'images' => []
        ];
        if (empty($ids)) return $resault;
        $list = File::whereIn('id', $ids)->get();
        foreach ($list as $item) {
            if ($item->type == 'images'){
                $resault['images'][] = $item;
            }elseif($item->type == 'file'){
                $resault['files'][] = $item;
            }
        }
        return $resault;
    }

}